package im.oen.boot.api.dispatch.handler;

import im.oen.boot.api.annotation.handler.MethodAroundHandler;
import im.oen.boot.api.dao.AbsDao;
import im.oen.boot.api.entity.AbsEntity;
import im.oen.boot.common.utils.JsonUtil;
import org.springframework.data.domain.Example;

import java.io.Serializable;
import java.util.List;

/**
 * @author Kevin.Xu
 */
public class FindMethodHandler implements MethodHandler {
    @Override
    public String cmd() {
        return "find";
    }

    @Override
    public <T extends AbsEntity, ID extends Serializable> Object handler(AbsDao<T, ID> dao, MethodAroundHandler<T> methodAroundHandler, Class<T> entity, String[] paths, String body) {
        boolean emptyHandler = methodAroundHandler == null;
        List list = null;
        if (body == null || body.isEmpty()) {
            if (!emptyHandler) {
                methodAroundHandler.findBefore(null);
                list = methodAroundHandler.overrideFind(dao, null);
            }
            if (list == null) {
                list = dao.findAll();
            }
        } else {
            T obj = JsonUtil.safeToObj(body, entity);
            if (!emptyHandler) {
                methodAroundHandler.findBefore(obj);
                list = methodAroundHandler.overrideFind(dao, obj);
            }
            if (list == null) {
                Example<T> example = Example.of(obj);
                list = dao.findAll(example);
            }
        }
        if (!emptyHandler) {
            methodAroundHandler.findAfter(list);
        }
        return list;
    }
}
